package ofpof.web.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.captcha.Captcha;
import nl.captcha.servlet.CaptchaServletUtil;
import ofpof.domain.CaptchaToken;
import ofpof.service.CaptchaService;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class CaptchaController {

	@Autowired
	private CaptchaService captchaService;

	@RequestMapping(value = "/captcha/image/{captchaId}", method = RequestMethod.GET)
	public void renderCaptcha(@PathVariable ObjectId  captchaId, HttpServletRequest request, HttpServletResponse response) throws IOException {

		CaptchaToken captchaToken = captchaService.findValidTokenById(captchaId);
		if (captchaToken == null) {
			return ;
		}

		Captcha captcha = new Captcha.Builder(200, 50).addText().gimp().addNoise().addBorder().build();

		captchaToken.setCaptchaText(captcha.getAnswer());
		captchaService.updateCaptcha(captchaToken);
		CaptchaServletUtil.writeImage(response, captcha.getImage());
	}
}
